package com.tanhua.server.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.common.mapper.UserInfoMapper;
import com.tanhua.common.pojo.Announcement;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.common.vo.PageResult;
import com.tanhua.dubbo.api.HuanXinApi;
import com.tanhua.dubbo.api.QuanZiApi;
import com.tanhua.dubbo.api.UsersApi;
import com.tanhua.dubbo.pojo.Comment;
import com.tanhua.dubbo.pojo.HuanXinUser;
import com.tanhua.dubbo.pojo.Users;
import com.tanhua.server.vo.AnnouncementVo;
import com.tanhua.server.vo.MessageCommentVo;
import com.tanhua.server.vo.UserInfoVo;
import com.tanhua.server.vo.UsersVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author Don
 */
@Service
public class IMService {

    @Reference
    private HuanXinApi huanXinApi;

    @Reference
    private UsersApi usersApi;

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Reference
    private QuanZiApi quanZiApi;

    @Autowired
    private AnnouncementService announcementService;

    public UserInfoVo queryUserInfoByUserName(String userName) {
        // 查询环信账户
        HuanXinUser huanXinUser = huanXinApi.queryUserInfoByUserName(userName);
        if (ObjectUtil.isEmpty(huanXinUser)) {
            return null;
        }
        // 查询用户信息
        UserInfo userInfo = userInfoService.queryUserInfoByUserId(huanXinUser.getUserId());
        if (ObjectUtil.isEmpty(userInfo)) {
            return null;
        }
        // 封装UserInfoVo对象
        UserInfoVo userInfoVo = BeanUtil.copyProperties(userInfo, UserInfoVo.class, "marriage");
        userInfoVo.setGender(userInfo.getSex().toString().toLowerCase());
        userInfoVo.setMarriage(StrUtil.equals("已婚", userInfo.getMarriage()) ? 1 : 0);

        return userInfoVo;
    }

    /**
     * 添加好友
     *
     * @param friendId
     * @return
     */
    public Boolean contactUser(Long friendId) {
        // 获取当前用户id
        Long userId = UserThreadLocal.get().getId();
        // 保存好友关系到mongodb
        String id = usersApi.saveUsers(userId, friendId);

        if (ObjectUtil.isNotEmpty(id)) {
            // 注册好友关系到环信
            return huanXinApi.addUserFriend(userId, friendId);
        }
        return false;
    }

    /**
     * 查询好友列表
     *
     * @param page
     * @param pageSize
     * @param keyWord
     * @return
     */
    public PageResult queryContactsList(Integer page, Integer pageSize, String keyWord) {

        PageResult result = new PageResult();
        result.setPage(page);
        result.setPagesize(pageSize);

        // 获取用户id
        Long userId = UserThreadLocal.get().getId();
        // 查询所有好友
        List<Users> usersList = usersApi.queryUsersList(userId, page, pageSize);

        if (CollUtil.isEmpty(usersList)) {
            return result;
        }

        ArrayList<UsersVo> list = new ArrayList<>();

        for (Users users : usersList) {
            Long friendId = users.getFriendId();
            LambdaQueryWrapper<UserInfo> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(UserInfo::getUserId, friendId);
          /*  if(StrUtil.isNotEmpty(keyWord)){
                wrapper.like(UserInfo::getNickName,keyWord);
            }*/
            UserInfo userInfo = userInfoMapper.selectOne(wrapper);
            // 填充用户信息
            UsersVo usersVo = new UsersVo();
            usersVo.setId(userInfo.getUserId());
            usersVo.setAge(userInfo.getAge());
            usersVo.setAvatar(userInfo.getLogo());
            usersVo.setGender(userInfo.getSex().name().toLowerCase());
            usersVo.setNickname(userInfo.getNickName());
            //环信用户账号
            usersVo.setUserId("HX_" + String.valueOf(userInfo.getUserId()));
            usersVo.setCity(StringUtils.substringBefore(userInfo.getCity(), "-"));
            list.add(usersVo);
        }
        result.setItems(list);
        return result;
    }

    public PageResult queryLikeCommentList(Integer page, Integer pageSize) {
        // 获取用户id
        Long userId = UserThreadLocal.get().getId();

        List<Comment> commentList = quanZiApi.queryLikeCommentList(userId, page, pageSize);

        return fillUserCommentList(commentList, page, pageSize);

    }

    public PageResult queryUserCommentList(Integer page, Integer pageSize) {
        // 获取用户id
        Long userId = UserThreadLocal.get().getId();

        List<Comment> commentList = quanZiApi.queryUserCommentList(userId, page, pageSize);

        return fillUserCommentList(commentList, page, pageSize);
    }

    public PageResult queryLoveCommentList(Integer page, Integer pageSize) {
        // 获取用户id
        Long userId = UserThreadLocal.get().getId();

        List<Comment> commentList = quanZiApi.queryLoveCommentList(userId, page, pageSize);

        return fillUserCommentList(commentList, page, pageSize);
    }

    private PageResult fillUserCommentList(List<Comment> commentList, Integer page, Integer pageSize) {

        PageResult result = new PageResult();
        result.setPage(page);
        result.setPagesize(pageSize);

        if (CollUtil.isEmpty(commentList)) {
            // 没有查询到数据
            return result;
        }

        ArrayList<MessageCommentVo> list = new ArrayList<>();

        for (Comment comment : commentList) {
            Long commentUserId = comment.getUserId();
            UserInfo userInfo = userInfoService.queryUserInfoByUserId(commentUserId);

            MessageCommentVo messageCommentVo = new MessageCommentVo();
            messageCommentVo.setId(comment.getId().toHexString());
            messageCommentVo.setAvatar(userInfo.getLogo());
            messageCommentVo.setNickname(userInfo.getNickName());
            messageCommentVo.setCreateDate(DateUtil.format(new Date(comment.getCreated()), "yyyy-MM-dd HH:mm"));

            list.add(messageCommentVo);
        }
        result.setItems(list);
        return result;
    }

    public PageResult queryMessageAnnouncementList(Integer page, Integer pageSize) {

        IPage<Announcement> announcementPage = this.announcementService.queryList(page, pageSize);
        List<AnnouncementVo> announcementVoList = new ArrayList<>();

        for (Announcement record : announcementPage.getRecords()) {
            AnnouncementVo announcementVo = new AnnouncementVo();
            announcementVo.setId(record.getId().toString());
            announcementVo.setTitle(record.getTitle());
            announcementVo.setDescription(record.getDescription());
            announcementVo.setCreateDate(DateUtil.format(record.getCreated(), "yyyy-MM-dd HH:mm"));

            announcementVoList.add(announcementVo);
        }

        PageResult pageResult = new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pageSize);
        pageResult.setItems(announcementVoList);

        return pageResult;
    }

    /**
     * 删除好友关系
     *
     * @param userId
     * @return
     */
    public void removeUser(Long userId) {
        User user = UserThreadLocal.get();
        // 判断是否删除
        Boolean flag = this.usersApi.removeUsers(user.getId(), userId);

        // 确认删除
        if(flag){
            // 删除在环信上的好友关系
            this.huanXinApi.removeUserFriend(user.getId(),userId);
        }
    }
}

